import React, { useState, useEffect } from 'react';
import { AppstoreOutlined, MailOutlined, SettingOutlined } from '@ant-design/icons';
import { useNavigate } from 'react-router-dom';
import { Col, Row, message } from 'antd';
import { Menu } from 'antd';
import { logout } from '../../api/login';
import css from './index.module.less';

export default function index() {
	const navigate = useNavigate();
	const items = [
			{
				label: '首页',
				key: '/',
				icon: <MailOutlined />,
			},
			{
				label: '时间轴',
				key: '/timeroller',
				icon: <AppstoreOutlined />,
			},
			{
					label: '分类',
					key: '/category',
					icon: <SettingOutlined />,
				},
		];
    const [current, setCurrent] = useState('/');

    const onClick = (item) => {
    	const key = item.key;
			const i = sessionStorage.getItem('info')
			const info = JSON.parse(i);
			if (info === null) {
				message.error("请登录").then(r => {});
				navigate('/');
			} else {
				navigate(key);
				setCurrent(key);
			}
    };
    const style = {
        background: '#ffffff',
        padding: '8px 0',
    };
	const [info, setInfo] = useState();
	useEffect(() => {setInfo(JSON.parse(sessionStorage.getItem("info")))}, [info]);
	  const toLogin = () => {
			navigate("/login");
		}
		const loginout = () => {
			logout().then((res) => {
				console.log(res)
				if (res.code === 200) {
					sessionStorage.removeItem("info");
					sessionStorage.removeItem("authorization");
					setInfo(JSON.parse(sessionStorage.getItem("info")));
					message.success("注销成功");
					navigate("/login");
				} else {
					message.error("注销失败");
				}
			})
		}
    return (
        <>
          <Row className={css.header}>
            <Col className="gutter-row" span={14}>
                <div style={style} className={css.title}>{info === null || info === undefined ? "游客" : info.username }</div>
            </Col>
            <Col className="gutter-row" span={8}>
              <Menu className={css.link} onClick={onClick} selectedKeys={[current]} mode="horizontal" items={items} />
            </Col>
						<Col className="gutter-row" span={2}>
							{info === null || info === undefined ?
								<div style={style} className={css.login} onClick={toLogin}>登录</div> :
								<div style={style} className={css.login} onClick={loginout}>注销</div>
							}
						</Col>
          </Row>
        </>
    );
}
